package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class UtilDB<T> {
	private final String Driver="com.mysql.jdbc.Driver";
	private final String URL="jdbc:mysql:///test";
	private final String NAME="root";
	private final String PASSWORD="";
	private Connection conn=null;
	private PreparedStatement stat=null;
	private ResultSet rs=null;
	private List<T> list=new ArrayList<T>();
	
		public Connection getConnection(){
			try {
				Class.forName(Driver);
				conn=DriverManager.getConnection(URL, NAME, PASSWORD);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return conn;
		}
		
		public void close(ResultSet rs,PreparedStatement stat,Connection conn){
			try {
				if(rs!=null){
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					if(stat!=null){
						stat.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}finally{
					try {
						if(conn!=null){
							conn.close();
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}			
		}
		
		public void close(PreparedStatement stat,Connection conn){
			close(null,stat,conn);
		}
		
		public boolean executeSQL(String sql,Object... args){
			try {
				stat=getConnection().prepareStatement(sql);
				for (int i = 0; i < args.length; i++) {
					stat.setObject(i+1, args[i]);
				}
				int row=stat.executeUpdate();
				if(row>0){
					return true;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				close(stat,conn);
			}
			return false;
		}
		
		public List<T> executeQueryForList(String sql,RowMapper<T> rm,Object... args){
			try {
				stat=getConnection().prepareStatement(sql);
				for (int i = 0; i < args.length; i++) {
					stat.setObject(i+1, args[i]);
				}
				rs=stat.executeQuery();
				while(rs.next()){
					T obj=rm.rowMapper(rs);
					list.add(obj);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				close(rs,stat,conn);
			}	
			return list;
		}
		

		public T executeQueryForObject(String sql,RowMapper<T> rm,Object... args){
			T obj=null;
			try {
				stat=getConnection().prepareStatement(sql);
				for (int i = 0; i < args.length; i++) {
					stat.setObject(i+1, args[i]);
				}
				rs=stat.executeQuery();
				if(rs.next()){
					obj=rm.rowMapper(rs);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				close(rs,stat,conn);
			}
			return obj;	
			
		}
}
